import { useState, useEffect, useCallback } from 'react';
import { userService } from '../services';
import { User } from '../types';
import { useAuth } from '../modules/profile/UserContext';
import { LoginCredentials as AuthLoginCredentials } from '../modules/profile/types';

// 登录凭据接口
export interface LoginCredentials {
  phone: string;
  code: string;
}

// 注册凭据接口
export interface RegisterCredentials {
  phone: string;
  code: string;
}

// 登录响应接口
export interface LoginResponse {
  token: string;
  user: User;
}

export const useUser = () => {
  const {
    user,
    isLoading: loading,
    error,
    login: authLogin,
    logout: authLogout,
    updateUser: updateAuthUser,
  } = useAuth();
  const [operationLoading, setOperationLoading] = useState<boolean>(false);
  const [operationError, setOperationError] = useState<string | null>(null);

  // 用户注册
  const register = useCallback(async (credentials: RegisterCredentials) => {
    setOperationLoading(true);
    setOperationError(null);

    try {
      const response = await userService.register(credentials);
      return response;
    } catch (err: any) {
      const errorMessage = err.message || 'Registration failed';
      setOperationError(errorMessage);
      console.error('Registration error:', err);
      throw err;
    } finally {
      setOperationLoading(false);
    }
  }, []);

  // 更新用户信息
  const updateProfile = useCallback(
    async (userData: Partial<User>) => {
      setOperationLoading(true);
      setOperationError(null);

      try {
        const updatedUser = await userService.updateProfile(userData);
        updateAuthUser(updatedUser);
        return updatedUser;
      } catch (err: any) {
        const errorMessage = err.message || 'Failed to update profile';
        setOperationError(errorMessage);
        console.error('Update profile error:', err);
        throw err;
      } finally {
        setOperationLoading(false);
      }
    },
    [updateAuthUser],
  );

  // 登录函数，适配AuthContext的LoginCredentials类型
  const login = useCallback(
    async (credentials: AuthLoginCredentials) => {
      await authLogin(credentials);
    },
    [authLogin],
  );

  return {
    user,
    loading: operationLoading || loading,
    error: operationError || error,
    login,
    logout: authLogout,
    register,
    updateProfile,
  };
};
